package service

import (
	"context"
	v1 "docker-api/api/v1"
	"docker-api/internal/domain"
	"docker-api/internal/repository"
	"docker-api/pkg/cmd"
)

type DockerInfoService interface {
	// 版本信息
	GetDockerVersion(ctx context.Context) (*v1.DockerVersionResponse, error)
	// 获取 Docker 服务状态
	GetDockerStatus(ctx context.Context) (*domain.DockerServiceStatus, error)
	// 文档管理
	GetDockerDocs(ctx context.Context) ([]v1.DockerDocResponse, error)
}

func NewDockerInfoService(
	service *Service,
	versionRepo repository.DockerVersionRepository,
	docRepo repository.DockerDocRepository,
) DockerInfoService {
	return &dockerInfoService{
		Service:     service,
		versionRepo: versionRepo,
		docRepo:     docRepo,
	}
}

type dockerInfoService struct {
	*Service
	versionRepo repository.DockerVersionRepository
	docRepo     repository.DockerDocRepository
}

func (s *dockerInfoService) GetDockerVersion(ctx context.Context) (*v1.DockerVersionResponse, error) {
	version, err := s.versionRepo.GetDockerVersion(ctx)
	if err != nil {
		return nil, err
	}
	return &v1.DockerVersionResponse{
		DockerVersion:  version.DockerVersion,
		OsVersion:      version.OsVersion,
		ComposeVersion: version.ComposeVersion,
	}, nil
}

func (s *dockerInfoService) GetDockerDocs(ctx context.Context) ([]v1.DockerDocResponse, error) {
	// 使用正确的仓储方法获取文档
	docs, err := s.docRepo.GetDockerDoc(ctx)
	if err != nil {
		return nil, err
	}

	// 创建响应切片
	responses := make([]v1.DockerDocResponse, len(docs))
	// 直接复制结构体字段，因为字段名称和类型完全匹配
	for i, doc := range docs {
		responses[i] = v1.DockerDocResponse(doc)
	}

	return responses, nil
}

// GetDockerStatus 获取 Docker 服务状态
func (s *dockerInfoService) GetDockerStatus(context.Context) (*domain.DockerServiceStatus, error) {
	isRunning := cmd.IsDockerRunning()

	status := &domain.DockerServiceStatus{}
	if isRunning {
		status.Status = "running"
		status.Message = "Docker 服务正在运行"
	} else {
		status.Status = "stopped"
		status.Message = "Docker 服务未运行或无法访问"
	}

	return status, nil
}
